<?php

namespace app\admin\controller;

use app\admin\model\AdminGroup;
use app\admin\model\AdminMenu;

class AdminGroupController extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }
    public function read()
    {
        $model = new AdminGroup();
        if (isset($_GET['type']) && $_GET['type']  == 'tree'){
            $data =(new AdminMenu())->select();

            $checked = $this->request->get("checked");
            foreach ($data as $key=>$item) {
                    if (in_array($item['menu_id'], explode(',', $checked))){
                      $data[$key]['checked'] =true;
                    }else{
                        $data[$key]['checked'] =false;
                    }
            }
            $alias = ['menu_name' => 'name', 'menu_parent_id' => 'pid', 'menu_id' => 'value','checked'=>'checked'];
            $tree_list = tree($data, 'menu_id', $alias,'list');
            return json(['code'=>0,'msg'=>'数据返回成功','data'=>$tree_list]) ;
        }
        $data = $model->page(input('get.page', input('get.limit')))->select();
        return json(['code' => 0, 'msg' => '数据返回成功', 'data' => $data]);
    }
    public function add()
    {
        $data = (new  AdminGroup())->save(input('post.'));
        if ($data) {
            return json(['code' => 0, 'msg' => '添加成功']);
        } else {
            return json(['code' => 500, 'msg' => '添加失败']);
        }

    }
    public function upd()
    {
        $data = (new  AdminGroup())->isUpdate(true)->save(input('post.'));
        if ($data) {
            return json(['code' => 0, 'msg' => '更新成功']);
        } else {
            return json(['code' => 500, 'msg' => '更新失败']);
        }

    }
    public function  del(){
        $result =AdminGroup::get(input('post.'))->delete();
        if($result){
            return json(['code'=>0,'msg'=>'删除成功']);
        }else{
            return json(['code'=>500,'msg'=>'删除失败']);
        }
    }
}
